﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Bll;
using Runda.CMS.Common.Utility;
using Runda.CMS.Common.Entity;
using System.Data;

namespace Runda.CMS.Portal.ContractFollowUp
{
    public partial class MaintainBillList : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["customername"] != null)
                    txtContractCodeBasic.Text = Request.QueryString["customername"].ToString();
                if (Request.QueryString["instrumentname"] != null)
                    txtinstrumentName.Text = Request.QueryString["instrumentname"].ToString();
                TaskType.BindEnum(EnumeratorHelper.GetFieldTexts(typeof(Enumerator.SalesService)));
                TaskType.Items.Add(new ListItem("--不限--", "0"));
                TaskType.SelectedValue = "0";
                BindList(1);
            }
        }

        private void BindList(int pageindex)
        {
            string Whereclause = "";
            Whereclause = getQuerysql();
            int RecordCount = 0;
            DataTable dt = new MaintainBillBll().QueryMaintainBll(Whereclause, "BeginDate desc", AspNetPager1.PageSize, pageindex, out RecordCount);

            RepeaterUsers.DataSource = dt;
            RepeaterUsers.DataBind();
            AspNetPager1.RecordCount = RecordCount;
        }
             
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindList(AspNetPager1.CurrentPageIndex);
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindList(1);
        }

        protected void RepeaterUsers_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {

                Label MaintainID = e.Item.FindControl("MaintainID") as Label;
                Label CustomerID = e.Item.FindControl("CustomerID") as Label;
                Label CustomerName = e.Item.FindControl("CustomerName") as Label;
                 Label Maintainer = e.Item.FindControl("Maintainer") as Label;
                Label MaintainerName = e.Item.FindControl("MaintainerName") as Label;
              
                Label TaskType = e.Item.FindControl("TaskType") as Label;
                Label TaskTypeName = e.Item.FindControl("TaskTypeName") as Label;
                //Label BeginDate = e.Item.FindControl("BeginDate") as Label;
                //Label EndTime = e.Item.FindControl("EndTime") as Label;
                Label CustomerArea = e.Item.FindControl("CustomerArea") as Label;
                Label InstrumentID = e.Item.FindControl("InstrumentID") as Label;
                Label Instrumentname = e.Item.FindControl("Instrumentname") as Label;
                Label RegisterID = e.Item.FindControl("RegisterID") as Label;
                Label IsSystemAssign = e.Item.FindControl("IsSystemAssign") as Label;
                Label changeAccessory = e.Item.FindControl("changeAccessory") as Label;
                
                if (MaintainID.Text != "")
                { 
                    List<WsmAccessoryReplacementEntity> instruments = new SystemBll().GetAll<WsmAccessoryReplacementEntity>(" and MaintainID = '" + MaintainID.Text + "'");
                    if (instruments != null && instruments.Count > 0)
                    { changeAccessory.Text = "√"; changeAccessory.ForeColor = System.Drawing.Color.Red; }
                }
                if (CustomerID != null)
                {
                    CtrtCustomerEntity entity = new SystemBll().Get<CtrtCustomerEntity>(new Guid(CustomerID.Text));
                    CustomerName.Text = entity.CustomerName;
                   
                    if (Maintainer.Text.Trim() != "")
                    {
                        SysUserEntity sysuserentity = new SystemBll().GetUserEntityFromCache(new Guid(Maintainer.Text));
                        if(sysuserentity != null)
                        MaintainerName.Text = sysuserentity.UserName;
                    }
                    //List<WsmMaintainBillEntity> entitys = new SystemBll().GetAll<WsmMaintainBillEntity>(" and RegisterID = '" + RegisterID.Text + "'");
                    //BeginDate.Text = entitys[0].BeginDate.ToString();
                    //EndTime.Text = entitys[0].EndTime.ToString();
                    TaskTypeName.Text = EnumeratorHelper.GetFieldText((Enumerator.SalesService)Convert.ToInt32(TaskType.Text));
                    if (IsSystemAssign.Text == "False" && (TaskType.Text == "3" || TaskType.Text == "6" || TaskType.Text == "7")) { TaskTypeName.Text += "(应需)"; }
                    if (IsSystemAssign.Text == "True" && (TaskType.Text == "3" || TaskType.Text == "6" || TaskType.Text == "7")) { TaskTypeName.Text += "(计划)"; } 
                   
                    WsmCustomerExtensionEntity extensionEntity = new SystemBll().Get<WsmCustomerExtensionEntity>(new Guid(CustomerID.Text));
                    if (extensionEntity != null)
                        CustomerArea.Text = extensionEntity.CustomerArea;

                    if (InstrumentID.Text != "")
                    {
                        WsmInstrumentInfoEntity insurment = new SystemBll().Get<WsmInstrumentInfoEntity>(new Guid(InstrumentID.Text));
                        if (insurment != null)
                            Instrumentname.Text = insurment.instrumentName;
                    }
                }
               
            }
            if (e.Item.ItemType == ListItemType.Footer)
            {
                Label sum1 = e.Item.FindControl("sum1") as Label;
                Label sum2 = e.Item.FindControl("sum2") as Label;

                if (sum1 != null)
                {
                    string Whereclause = "";
                    Whereclause = getQuerysql();
                    DataRow dr = new MaintainBillBll().TotalCustomerServices(Whereclause).Rows[0];
                    sum1.Text = dr["custs"].ToString() + "个客户";
                    sum2.Text = dr["serviceCount"].ToString() + "个服务单";

                }
            }
        }

        private string getQuerysql()
        {
            string Whereclause = "";

            if (txtContractCodeBasic.Text.Trim() != "")
            {
                Whereclause += " and CustomerID in ( select CustomerID from vw_CustomerAllInfo where CustomerName like '%" + txtContractCodeBasic.Text.Trim() + "%' or  CustomerArea like '%" + txtContractCodeBasic.Text.Trim() + "%')";
            }

            if (this.txtSerialNum.Text.Trim() != "")
            {
                Whereclause += " and tt.InstrumentSerialNum  like '%" + txtSerialNum.Text.Trim() + "%'";
            }

            if (this.txtinstrumentName.Text.Trim() != "")
            {
                Whereclause += " and InstrumentID in ( select InstrumentID from Cms_Wsm_InstrumentInfo where InstrumentName like '%" + txtinstrumentName.Text.Trim() + "%')";
            }

            if (TaskType.SelectedValue.ToString() != "0")
            {
                Whereclause += " and TaskType = " + TaskType.SelectedValue.ToString();
            }
            if (maintainer.Text.Trim() != "")
            {
                Whereclause += " and Maintainer in(select userid from cms_sys_user where username like '" + maintainer.Text.Trim().ToString() + "%')";
            }
            if (BeginDateFrom.SelectedDate != null)
            {
                Whereclause += " and BeginDate>='" + BeginDateFrom.SelectedDate.ToString() + "'";
            }
            if (BeginDateTo.SelectedDate != null)
            {
                Whereclause += " and BeginDate<='" + BeginDateTo.SelectedDate.ToString() + "'";
            }
            if (EndtimeFrom.SelectedDate != null)
            {
                Whereclause += " and Endtime>='" + EndtimeFrom.SelectedDate.ToString() + "'";
            }
            if (EndtimeTo.SelectedDate != null)
            {
                Whereclause += " and Endtime<='" + EndtimeTo.SelectedDate.ToString() + "'";
            }
            if (listIsInWorkingTime.SelectedValue != "-1") {
                Whereclause += " and IsInWorkingTime =" + listIsInWorkingTime .SelectedValue;
            }
            if (txtFaultCode.Text.Trim() != "")
            {
                Whereclause += " and FaultCode='" + txtFaultCode.Text.Trim() + "'";
            }

            if (txtFaultComponents.Text.Trim() != "")
            {
                 Whereclause += " and FaultComponents like '%"+txtFaultComponents.Text.Trim()+"%'";
            }

            if (chkAccessory.Checked)
            { Whereclause += " and AccessoryID is not null"; }

            return Whereclause;
        }

        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            string Whereclause = "";

            Whereclause = getQuerysql();


            MaintainBillBll bll = new MaintainBillBll();

            DataTable dt = bll.ExportMaintainBills(Whereclause);

            DataRow dr = new MaintainBillBll().TotalCustomerServices(Whereclause).Rows[0];

            DataRow dr_new = dt.NewRow();
            dr_new["客户名称"] = dr["custs"].ToString() + "个客户";
            dr_new["仪器名称"] = dr["serviceCount"].ToString() + "个服务单";

            dt.Rows.Add(dr_new);
            Export.Export2Excel(dt, "服务单一览表", Page.Response);

        }
    }
}
